package com.jinyu.jyly.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hjm.bottomtabbar.BottomTabBar;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseActivity;

import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.ConfigInfo;
import com.jinyu.jyly.bean.NoticeInfo;
import com.jinyu.jyly.bean.UpdateInfo;
import com.jinyu.jyly.global.GlobalConstants;
import com.jinyu.jyly.ui.community.CommunityFragment;
import com.jinyu.jyly.ui.mall.MallFragment;
import com.jinyu.jyly.ui.home.HomeFragment;
import com.jinyu.jyly.ui.mine.MineFragment;
import com.jinyu.jyly.ui.mine.buy.MineBuyActivity;
import com.jinyu.jyly.ui.mine.make_code.MakeCodeActivity;
import com.jinyu.jyly.ui.mine.passageway.PassageWayActivity;
import com.jinyu.jyly.ui.mine.sell.MineSellActivity;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.utils.APKVersionCodeUtils;
import com.jinyu.jyly.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import util.UpdateAppUtils;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, View.OnClickListener {

    @BindView(R.id.bottom_tab_bar)
    BottomTabBar bottom_tab_bar;
    private MainPresenter mPresenter;

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected MainPresenter getPresenter() {
        if (mPresenter == null) {
            mPresenter = new MainPresenter(this, this);
        }
        return mPresenter;
    }

    @Override
    protected void initEventAndData() {
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);


//        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, null);
        initView();
        initListener();
        mPresenter.getNotice();

        try {
            int versionCode = APKVersionCodeUtils.getVersionCode(this);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("version", versionCode);
            String param = AES.encryptToHexString(jsonObject1.toString());
            mPresenter.getUpdataApp(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initListener() {
        mPresenter.getConfig();
    }

    private void initView() {
        bottom_tab_bar.init(getSupportFragmentManager(), 720, 1280)
                .setImgSize(50, 50)
                .setFontSize(18)
                .setTabPadding(10, 0, 10)
//                .setChangeColor(Color.parseColor("#FF00F0"),Color.parseColor("#CCCCCC"))
                .addTabItem("首页", R.mipmap.bottom_home_press, R.mipmap.bottom_home_normal, HomeFragment.class)
                .addTabItem("商城", R.mipmap.bottom_shopstore_press, R.mipmap.bottom_shopstore_normal, MallFragment.class)
                .addTabItem("社区", R.mipmap.bottom_shequ_press, R.mipmap.bottom_shequ_normal, CommunityFragment.class)
                .addTabItem("我的", R.mipmap.bottom_mine_press, R.mipmap.bottom_mine_normal, MineFragment.class)
//                .isShowDivider(true)
//                .setDividerColor(Color.parseColor("#FF0000"))
//                .setTabBarBackgroundColor(Color.parseColor("#00FF0000"))
                .setOnTabChangeListener(new BottomTabBar.OnTabChangeListener() {
                    @Override
                    public void onTabChange(int position, String name, View view) {
//                        if (position == 3)
//                            bottom_tab_bar.setSpot(3, false);
                    }
                });

    }


    @Override
    public void onFailer(Throwable throwable) {

    }

    @Override
    public void onUpdatApp(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                try {
                    String info = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    UpdateInfo updateInfo = gson.fromJson(info, UpdateInfo.class);
                    if (updateInfo != null) {
                        int version = updateInfo.getVersion();
                        String new_version = updateInfo.getNew_version();
                        String apk_file_url = updateInfo.getApk_file_url();
                        String update_log = updateInfo.getUpdate_log();
                        int constraint = updateInfo.getConstraint();

                        String log = "优化了用户体验";
                        if (!TextUtils.isEmpty(update_log)) {
                            String[] split = update_log.split("/n");
                            for (int i = 0; i < split.length; i++) {
                                log = log + "\n" + split[i];
                            }
                        }

                        UpdateAppUtils.from(MainActivity.this)
                                .serverVersionCode(version)
                                .serverVersionName(new_version)
                                .apkPath(apk_file_url)
                                .updateInfo(log)
                                .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
                                .showNotification(true)
                                .isForce(constraint == 1 ? true : false) //是否强制更新
//                          .needFitAndroidN(false)
                                .update();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                break;
            default:
                break;
        }
    }


    @Override
    public void onGetConfig(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                try {
                    String info = AES.decrypt(data);
                    Gson gson = new Gson();
                    ConfigInfo configInfo = gson.fromJson(info, ConfigInfo.class);
                    if (configInfo != null) {
                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.LOGIN_PROMOTION, configInfo.getPromotion());
                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.SHARE_LINK, configInfo.getShare_link());
                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.IN_NUM, configInfo.getIn_num());

                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.QINIU_TOKEN, configInfo.getQi_token());

                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.CONFIG_RECHARGE_RATE, configInfo.getRecharge_rate());
                        SharedPreferencesUtils.setParam(MainActivity.this, GlobalConstants.CONFIG_RECHARGE_MIN, configInfo.getRecharge_min());

                        Log.e("yaoqingma", configInfo.getPromotion());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 获取通知消息
     *
     * @param infoBean
     */
    @Override
    public void onNotice(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                try {
                    String info = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    NoticeInfo noticeInfo = gson.fromJson(info, NoticeInfo.class);
                    if (noticeInfo != null) {
                        int get = noticeInfo.getGet();
                        int green = noticeInfo.getGreen();
                        int pay = noticeInfo.getPay();
                        int pic = noticeInfo.getPic();

                        if (get == 1 || green == 1 || pay == 1 || pic == 1) {
                            if (get == 1) {
                                setSignOutApp("确认收款提示", "您有未确认收款订单，点击前往",0);
                            }

                            if (green == 1) {
                                setSignOutApp("未预排提示", "您有未预排消息，点击前往",1);
                            }

                            if (pay == 1) {
                                setSignOutApp("未付款提示", "您有未付款订单，点击前往",2);
                            }

                            if (pic == 1) {
                                setSignOutApp("提示", "您还未添加收款码，点击前往",3);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {

    }

    //提示
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private void setSignOutApp(String title, String content,int type) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle(title)
                .setMessage(content)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        switch (type){
                            case 0:
                                //确认收款提示
                                Intent msellIntent = new Intent(MainActivity.this, MineSellActivity.class);
                                msellIntent.putExtra("type", "我的卖单");
                                startActivity(msellIntent);
                                break;
                            case 1:
                                //未预排提示
                                Intent mpasswayIntent = new Intent(MainActivity.this, PassageWayActivity.class);
                                startActivity(mpasswayIntent);
                                break;
                            case 2:
                                //未付款订单
                                Intent mbuyIntent = new Intent(MainActivity.this, MineBuyActivity.class);
                                mbuyIntent.putExtra("type", "我的买单");
                                startActivity(mbuyIntent);
                                break;
                            case 3:
                                //未添加收款码
                                Intent mCodeIntent = new Intent(MainActivity.this, MakeCodeActivity.class);
                                startActivity(mCodeIntent);
                                break;
                            default:break;
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

}
